<template>
  <div class="gnpermissio">
    <el-form>
      <!--1. show-checkbox 显示选择框
          2. default-expand-all 默认展开
          3. check-strictly  设置true，可以关闭父子关联
      -->
      <el-tree
        ref="refTree"
        :data="permissionData"
        :props="{ label: 'name' }"
        default-expand-all
        :show-checkbox="true"
        :check-strictly="true"
        node-key="id"
      />
      <el-form-item style="text-align: right">
        <el-button @click="hCancel">取消</el-button>
        <el-button type="primary" @click="hSave">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permisson.js'
import { ToDoLostData } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/setting.js'
export default {
  name: 'VueAdminTemplateAssignpermission',
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionData: [] // 存储权限数据
    }
  },
  created() {
    // 获取权限点
    this.loadPermissionList()
    // 获取角色详情权限
    this.loadPermissionByRoleId()
  },

  mounted() {},

  methods: {
    hCancel() {
      // 通过父组件去关闭弹层
      this.$emit('close')
    },
    // 获取权限点
    async loadPermissionList() {
      const { data } = await getPermissionList()
      // 将数据处理成树形结构
      this.permissionData = ToDoLostData(data, '0')
    },
    // 获取角色详情权限
    async loadPermissionByRoleId() {
      const { data } = await getRoleDetail(this.roleId)
      // 回填
      // 在el-tree组件中通过 setCheckedKeys方法+ node-key 将数据 回显到el-tree组件中：处于选中状态
      this.$refs.refTree.setCheckedKeys(data.permIds)
    },
    // 调用api分配权限-功能实现
    async hSave() {
      // 通过el-tree组件的 getCheckedKeys 来获取用户选中的id列表
      const permIds = this.$refs.refTree.getCheckedKeys()
      await assignPerm({ id: this.roleId, permIds })
      // 提示
      this.$message.success('保存角色的权限成功')
      // 关闭弹层
      this.hCancel()
    }
  }
}
</script>

<style lang="scss" scoped>
.gnpermissio {
  padding: 30px 20px;
}
</style>

<style lang="scss">
.el-dialog__body {
  padding: 0;
}
</style>
